package com.fbinggun.dt.player;

import com.alibaba.fastjson.JSONObject;
import com.fbinggun.dt.DailyTask;
import com.fbinggun.dt.task.Task;
import com.fbinggun.dt.task.conditions.Conditions;
import com.fbinggun.fbinggunutil.TiemUtil;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

public class PlayerTask {
    Task task;
    Map<String,Double> data = new HashMap<>();
    Long tiemLimit;

    public PlayerTask(Task task, Long tiemLimit) {
        this.task = task;
        this.tiemLimit = TiemUtil.date()+tiemLimit*1000;
    }

    public PlayerTask(JSONObject json){
        this.task= DailyTask.getTask(json.getString("Task"));
        this.tiemLimit=json.getLong("TiemLimit");
        JSONObject jsonData = json.getJSONObject("Conditions");
        if(jsonData!=null){
            for(String key:jsonData.keySet()){
                double count = jsonData.getDouble(key);
                data.put(key,count);
            }
        }
    }

    public Task getTask() {
        return task;
    }

    public void addCount(Conditions conditions, double a){
        double count = getCount(conditions);
        count=count+a;
        System.out.println("任务完成数量："+count);
        data.put(conditions.getId(),count);

    }
    public void addCount(String id,double a){
        double count = getCount(id);
        count=count+a;
        data.put(id,count);
    }

    public double getCount(String id){
        DecimalFormat df = new DecimalFormat("#.00");
        double count =data.getOrDefault(id,0d);
        return Double.parseDouble(df.format(count));
    }
    public double getCount(Conditions conditions){
        DecimalFormat df = new DecimalFormat("#.00");
        double count =Math.min(data.getOrDefault(conditions.getId(),0d),conditions.getCount());
        return Double.parseDouble(df.format(count));
    }

    public void setCount(Conditions conditions,double a){
        data.put(conditions.getId(),a);
    }
    public void setCount(String id,double a){
        data.put(id,a);
    }

    public boolean isOverdue(){
        if(TiemUtil.date()>=tiemLimit){
            return true;
        }
        return false;
    }
    public JSONObject toJson(){
        JSONObject json = new JSONObject();
        json.put("Task",task.getId());
        json.put("TiemLimit",tiemLimit);
        JSONObject jsonData = new JSONObject();
        if(data!=null&&data.size()!=0){
            for(String id:data.keySet()){
                jsonData.put(id,data.get(id));
            }
            json.put("Conditions",jsonData);
        }
        return json;
    }

    public Long getTiemLimit() {
        return tiemLimit;
    }

    public String getTiemLimitString() throws Exception {
        return TiemUtil.stampToTimeMillisecond(tiemLimit,"yyyy年MM月dd日 HH:mm:ss");
    }
}
